package com.realbrand.net.realbrandpay.ui.activity.shopcar;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.AuthTask;
import com.alipay.sdk.app.PayTask;
import com.realbrand.net.realbrandpay.APP;
import com.realbrand.net.realbrandpay.R;
import com.realbrand.net.realbrandpay.alipay.AuthResult;
import com.realbrand.net.realbrandpay.alipay.PayResult;
import com.realbrand.net.realbrandpay.api.HTTPAPI;
import com.realbrand.net.realbrandpay.base.BaseActivity;
import com.realbrand.net.realbrandpay.bean.BundleBean;
import com.realbrand.net.realbrandpay.bean.GetAuthCode;
import com.realbrand.net.realbrandpay.bean.ShopcarBean;
import com.realbrand.net.realbrandpay.db.DBManger;
import com.realbrand.net.realbrandpay.inter.IAuthorized;
import com.realbrand.net.realbrandpay.inter.IGetAuthInfo;
import com.realbrand.net.realbrandpay.inter.IPacketRecord;
import com.realbrand.net.realbrandpay.inter.IPaymentSelectOrder;
import com.realbrand.net.realbrandpay.inter.IPaymentUnPaidOrder;
import com.realbrand.net.realbrandpay.ui.activity.wallet.bill.BillActivity;
import com.realbrand.net.realbrandpay.untils.Constant;
import com.realbrand.net.realbrandpay.untils.Static;
import com.realbrand.net.realbrandpay.weight.EditTextJudgeNumberWatcher;
import com.realbrand.net.realbrandpay.weight.RadioGroup;
import com.realbrand.net.realbrandpay.zxing.util.L;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by Administrator on 2017/6/20.
 */

public class CheckOutActivity extends BaseActivity implements View.OnClickListener, RadioGroup.OnCheckedChangeListener {


    @BindView(R.id.checkOut_toolBar)
    Toolbar checkOutToolBar;
    @BindView(R.id.checkOut_et_importMoney)
    EditText checkOutEtImportMoney;
    //    @BindView(R.id.checkOut_bt_payByJianHang)
//    RadioButton checkOutBtPayByJianHang;
    @BindView(R.id.checkOut_bt_payByZhiFuBao)
    RadioButton checkOutBtPayByZhiFuBao;
    @BindView(R.id.checkOut_bt_payByWeiXin)
    RadioButton checkOutBtPayByWeiXin;
    @BindView(R.id.checkout_bt_checkout)
    Button checkoutBtCheckout;
    @BindView(R.id.checkout_rg)
    RadioGroup checkoutRg;
    @BindView(R.id.check_tv_store)
    TextView checkTvStore;
//    @BindView(R.id.checkOut_bt_payByPingAn)
//    RadioButton checkOutBtPayByPingAn;

    //选择哪一种支付方式的标识
    private int mInt = 5;

    //所以扫过的商品码集合
    private List<String> list;

    //数据库里面数据的数量
    private int countSQL;
    List<ShopcarBean> query;

    //扫过的商品码进行编码
    private String encodeScan;

    //购物车里商品信息进行编码；
    private String encodeData;

    //总额信息进行编码
    private String encodeAll;

    //红包参数进行编码
    private String encodeHb;

    public AlertDialog dialog;

    //订单号
    private String order;

    //支付用户
    private String userName;

    //支付宝参数
    public static final int SDK_PAY_FLAG = 1;
    public static final int SDK_AUTH_FLAG = 2;
    public static final int CHANGE_UI_ALIPAY = 11;
    public static final int CHANGE_UI_WX = 22;
    private Object result;


    //红包数组
    private JSONArray data;

    //红包标识
    private int mI = 0;

    private String payMoneyByUser;


    private SharedPreferences sharedPreferences;
    String forWhere;
    BundleBean b;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        L.d(L.TAG, "重新调用CheckOut");
        Bundle bundle = getIntent().getExtras();
        forWhere = bundle.getString("forWhere", "");
        checkOutToolBar.setTitle("");
        checkOutToolBar.setNavigationIcon(R.mipmap.ic_back);
        setSupportActionBar(checkOutToolBar);
        checkOutToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (forWhere.equals("check")) {
                    startActivity(new Intent(CheckOutActivity.this, ShopCarActivity.class));
                    finish();
                } else if (forWhere.equals("pick")) {
                    finish();
                }
            }
        });
        //订阅事件
        EventBus.getDefault().register(this);
        //拿到总消费额度
        sharedPreferences = getSharedPreferences(Constant.shareName, MODE_PRIVATE);
        String string = sharedPreferences.getString(Constant.shopCarMoney, "");
        //获取用户账号
        userName = sharedPreferences.getString("account", "");
        String store = sharedPreferences.getString("store", "");
        checkTvStore.setText(store);
        checkOutEtImportMoney.setEnabled(false);
        checkOutEtImportMoney.setText(string);
        //先判断商家支持的支付方式,然后显示
        checkOutEtImportMoney.addTextChangedListener(new EditTextJudgeNumberWatcher(checkOutEtImportMoney));
        if (APP.supportAlipay) {
            checkOutBtPayByZhiFuBao.setVisibility(View.VISIBLE);
            checkOutBtPayByZhiFuBao.setEnabled(true);
            String alipayName = sharedPreferences.getString("alipayName", "");
            if (!"".equals(alipayName)) {
                checkOutBtPayByZhiFuBao.setText("支付宝\n" + alipayName);
            }
        }
        if (APP.supportWX) {
            checkOutBtPayByWeiXin.setVisibility(View.VISIBLE);
            checkOutBtPayByWeiXin.setEnabled(true);
            String WXName = sharedPreferences.getString("WXName", "");
            if (!"".equals(WXName)) {
                checkOutBtPayByWeiXin.setText("微信\n" + WXName);
            }
        }
        if (forWhere.equals("check")) {
            //拿到所以扫过的商品码
//            APP app = (APP) getApplicationContext();
//            list = app.getList();
            //拿到数据库数据的数量
            DBManger dbManger = new DBManger(this);
            countSQL = dbManger.allCaseNum();
            L.d(L.TAG, "数据库的数据量" + countSQL);
            //从数据库抽取出所有数据
            query = dbManger.query();
        } else if (forWhere.equals("pick")) {
            b = (BundleBean) bundle.getSerializable("bean");
            L.d(L.TAG, "包装码界面过来的对象" + b.toString());
            list = new ArrayList<>();
            for (int n = 0; n < b.getList().size(); n++) {
                list.add(b.getList().get(n).getScan());
            }
        }
        checkoutRg.clearCheck();
        setOnClick();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.checkout_activity;
    }

    @Override
    protected void setOnClick() {
        checkoutBtCheckout.setOnClickListener(this);
        checkoutRg.setOnCheckedChangeListener(this);
    }


    @Override
    public void onClick(View v) {
        L.d(L.TAG, "结算");
        payMoneyByUser = checkOutEtImportMoney.getText().toString();
        if (new BigDecimal(new Double(payMoneyByUser)).compareTo(new BigDecimal(0.00)) == 0) {
            Static.toast(this, "请输入有效金额");
        } else {
            //判断用户选择的是哪种支付方式，然后判断用户此种支付方式是否已经授权，然后获取订单号进行支付
            switch (mInt) {
//                //龙支付
//                case 0:
//                    Static.toast(this, "暂未开通");
//                    break;
//                case 3:
//                    Static.toast(this, "暂未开通");
//                    break;
                //微信支付
                case 1:
                    if (Constant.wx_api.isWXAppInstalled()) {
                        if (APP.WXIsAuth) {
                            payMoney(mInt);
                        } else {
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                            String date = sdf.format(new Date());
                            authWX(date);
//                    payMoney(mInt);
                        }
                    } else {
                        Static.toast(this, "没有安装微信客户端");
                    }
                    break;
                //支付宝支付
                case 2:
                    L.d(L.TAG, "支付宝" + mInt);
                    if (APP.AlipayIsAuth) {
                        payMoney(mInt);
                    } else {
                        getAuth(mInt);
                    }
                    break;
                case 5:
                    Static.toast(this, "请选择支付方式");
                    break;
            }
        }


    }

    /**
     * 微信授权
     *
     * @param date
     */
    private void authWX(String date) {
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = date;
        Constant.wx_api.sendReq(req);
    }

    /**
     * 获取授权需要的字符串
     *
     * @param mInt
     */
    private void getAuth(final int mInt) {
        JSONObject authJson = new JSONObject();
        try {
            authJson.put("SOURCE", "CheckOutActivity");
            authJson.put("CREDENTIALS", "0");
            authJson.put("TERMINAL", "1");
            authJson.put("INDEX", Static.getDay());
            authJson.put("METHOD", "Authorized");
            authJson.put("PaymentMode", mInt);
            RequestBody body = RequestBody.create(HTTPAPI.JSON, authJson.toString());
            Retrofit retrofit = new Retrofit.Builder().baseUrl(HTTPAPI.PAY_BASE_URL).build();
            IAuthorized iAuthorized = retrofit.create(IAuthorized.class);
            Call<ResponseBody> authorized = iAuthorized.authorized(body);
            L.d(L.TAG, "支付宝授权请求成功发送" + mInt);
            authorized.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {

                        String string = response.body().string();
                        L.d(L.TAG, "获取授权字符串返回的结果" + string);
                        if (string.equals("")) {
                            Static.toast(CheckOutActivity.this, "网络繁忙");
                        } else {
                            JSONObject jsonObject = new JSONObject(string);
                            JSONArray data = jsonObject.getJSONArray("DATA");
                            String authString = data.getString(0);
                            auth(authString, mInt);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        L.d(L.TAG, "支付宝授权异常" + e.toString());
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    L.d(L.TAG, "支付宝授权异常" + t.toString());
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            L.d(L.TAG, "支付宝授权异常" + e.toString());
        }
    }

    /**
     * 授权
     *
     * @param authString 授权需要的字符串
     * @param mInt       哪种方式
     */
    private void auth(String authString, int mInt) {
        switch (mInt) {
//            //龙支付授权
//            case 0:
//                break;
            //微信授权
            case 1:
                break;
            //支付宝授权
            case 2:
                alipayAuth(authString);
                break;
        }
    }

    /**
     * 支付宝授权
     *
     * @param authString
     */
    private void alipayAuth(final String authString) {
        Runnable authRunnable = new Runnable() {
            @Override
            public void run() {
                AuthTask authTask = new AuthTask(CheckOutActivity.this);
                Map<String, String> result = authTask.authV2(authString, true);
                Message msg = new Message();
                msg.what = SDK_AUTH_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread authThread = new Thread(authRunnable);
        authThread.start();
    }


    /**
     * 获取订单号，发起请求
     *
     * @param mInt 表示哪一种支付方式
     */
    private void payMoney(final int mInt) {

        try {
            //已扫过的商品码
            list=new ArrayList<>();
            for (int i = 0; i < query.size(); i++) {
                list.add(query.get(i).getScan());
            }
            String scanCode = Static.stringScan(list);
            Log.d(L.TAG, "扫过的二维码" + scanCode);
            encodeScan = URLEncoder.encode(scanCode, "utf-8");
            //实际结算的所有商品
            List<List<String>> data = new ArrayList<>();
            List<String> listKey = new ArrayList<>();
            listKey.add("CommodityCode");
            listKey.add("PaymentMoney");
            listKey.add("UserAddress");
            data.add(listKey);

            //商品码的参数
            if (forWhere.equals("check")) {
                for (int i = 0; i < query.size(); i++) {
                    List<String> listValue = new ArrayList<>();
                    listValue.add(query.get(i).getScan());
                    listValue.add(query.get(i).getPrice() + "");
                    listValue.add(query.get(i).getAdress());
                    data.add(listValue);
                }

                //包装码的参数
            } else if (forWhere.equals("pick")) {
                for (int j = 0; j < b.getList().size(); j++) {
                    List<String> listValue = new ArrayList<>();
                    listValue.add(b.getList().get(j).getScan());
                    listValue.add(b.getList().get(j).getPrice());
                    listValue.add(b.getList().get(j).getAddress());
                    data.add(listValue);
                }

            }
            String dataString = Static.string(data);
            encodeData = URLEncoder.encode(dataString, "utf-8");

            //总额信息
            ArrayList<String> dataKey = new ArrayList<>();
            dataKey.add("UserAccount");
            dataKey.add("DealType");
            dataKey.add("DealMoney");
            dataKey.add("PaymentMode");
            dataKey.add("PaymentUser");
            ArrayList<String> dataValue = new ArrayList<>();
            if (forWhere.equals("check")) {
                dataValue.add(query.get(0).getApplyUser());
            } else if (forWhere.equals("pick")) {
                dataValue.add(b.getList().get(0).getUserAccount());
            }
            dataValue.add("0");
            dataValue.add(payMoneyByUser);
            dataValue.add(mInt + "");
            dataValue.add(userName);
            String allString = Static.getString(dataKey, dataValue);
            encodeAll = URLEncoder.encode(allString, "utf-8");

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("SOURCE", "CheckOutActivity");
            jsonObject.put("CREDENTIALS", "0");
            jsonObject.put("TERMINAL", "1");
            jsonObject.put("INDEX", Static.getDay());
            jsonObject.put("METHOD", "UnPaidOrder");
            jsonObject.put("ScanCode", encodeScan);
            jsonObject.put("DATA", encodeData);
            jsonObject.put("DATA1", encodeAll);
            RequestBody body = RequestBody.create(HTTPAPI.JSON, jsonObject.toString());
            Retrofit retrofit = new Retrofit.Builder().baseUrl(HTTPAPI.PAY_BASE_URL).build();
            IPaymentUnPaidOrder iPaymentUnPaidOrder = retrofit.create(IPaymentUnPaidOrder.class);
            Call<ResponseBody> call = iPaymentUnPaidOrder.UnPaidOrder(body);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    if (response == null) {
                        Static.toast(CheckOutActivity.this, "网络繁忙");
                    } else {
                        try {
                            String result = response.body().string();
                            L.d(L.TAG, "订单返回数据" + result);
                            JSONObject jsonResult = new JSONObject(result);
                            JSONArray jsonData = jsonResult.getJSONArray("DATA");
                            String orderInfo = jsonData.getString(0);
                            if (orderInfo.contains("sign")) {
                                order = jsonData.getString(1);
                                if (mInt == 1) {
                                    String replace = orderInfo.replace("\\\"", "\"");
                                    pay(replace, mInt);
                                    L.d(L.TAG, "++++++" + replace);
                                } else if (mInt == 2) {
                                    pay(orderInfo, mInt);
                                }
                            } else {
                                Static.toast(CheckOutActivity.this, "该商家暂停交易");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            L.d(L.TAG, "异常" + e.toString());
                        }
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    L.d(L.TAG, "获取订单失败" + t.toString());
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            L.d(L.TAG, "获取订单异常" + e.toString());
        }
    }

    /**
     * @param orderInfo 支付订单号
     * @param mInt      支付方式
     */
    private void pay(String orderInfo, int mInt) {
        switch (mInt) {
//            //龙支付
//            case 0:
//                break;
            //微信
            case 1:
                WXpay(orderInfo);
                break;
            //支付宝
            case 2:
                alipay(orderInfo);
                break;
        }
    }

    /**
     * 微信支付
     *
     * @param orderInfo
     */
    String appid;
    String noncestr;
    String aPackage;
    String partnerid;
    String prepayid;
    String sign;
    String timestamp;
    IWXAPI iwxapi;

    private void WXpay(final String orderInfo) {
        JSONObject wxJson = null;
        try {
            wxJson = new JSONObject(orderInfo);
            appid = wxJson.getString("appid");
            noncestr = wxJson.getString("noncestr");
            aPackage = wxJson.getString("package");
            partnerid = wxJson.getString("partnerid");
            prepayid = wxJson.getString("prepayid");
            sign = wxJson.getString("sign");
            timestamp = wxJson.getString("timestamp");
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putString("app_id", appid);
            edit.commit();
            iwxapi = WXAPIFactory.createWXAPI(this, appid, true);
            iwxapi.registerApp(appid);
            Runnable wxPay = new Runnable() {
                @Override
                public void run() {
                    PayReq request = new PayReq();
                    request.appId = appid;
                    request.partnerId = partnerid;
                    request.nonceStr = noncestr;
                    request.packageValue = aPackage;
                    request.prepayId = prepayid;
                    request.sign = sign;
                    request.timeStamp = timestamp;
                    Constant.wx_api.sendReq(request);
                }
            };
            Thread payThread = new Thread(wxPay);
            payThread.start();
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

    /**
     * 支付宝支付
     *
     * @param orderInfo
     */
    private void alipay(final String orderInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(CheckOutActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message message = new Message();
                message.what = SDK_PAY_FLAG;
                message.obj = result;
                mHandler.sendMessage(message);
            }
        };
        Thread thread = new Thread(payRunnable);
        thread.start();
    }

    /**
     * 支付宝支付结果返回
     */
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        //先获取请求后台需要的参数
                        ArrayList scan = new ArrayList();
                        if (forWhere.equals("check")) {
                            for (int j = 0; j < query.size(); j++) {
                                scan.add(query.get(j).getScan());
                            }
                        } else if (forWhere.equals("pick")) {
                            for (int j = 0; j < b.getList().size(); j++) {
                                scan.add(b.getList().get(j).getScan());
                            }
                        }
                        //请求后台拿到支付结果
                        new Thread() {
                            @Override
                            public void run() {
                                super.run();
                                try {
                                    sleep(2000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }.start();
                        getResult(scan, order);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(CheckOutActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                case SDK_AUTH_FLAG:
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        //获取授权code
                        new Thread() {
                            @Override
                            public void run() {
                                super.run();
                                try {
                                    sleep(2000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }.start();
                        String authCode = authResult.getAuthCode();
                        getAuthResult(authCode, 2);
                    } else {
                        Static.toast(CheckOutActivity.this, "授权失败");
                    }
                    break;
                case CHANGE_UI_ALIPAY:
                    String string = (String) msg.obj;
                    checkOutBtPayByZhiFuBao.setText("支付宝\n" + string);
                    break;
                case CHANGE_UI_WX:
                    String string1 = (String) msg.obj;
                    checkOutBtPayByWeiXin.setText("微信\n" + string1);
                    break;
            }
        }
    };

    /**
     * 请求服务器获取授权信息
     *
     * @param authCode 授权code
     * @param i        哪一种支付方式
     */
    private void getAuthResult(String authCode, final int i) {
        try {
            JSONObject getResultjson = new JSONObject();
            getResultjson.put("SOURCE", "CheckOutActivity");
            getResultjson.put("CREDENTIALS", "0");
            getResultjson.put("TERMINAL", "1");
            getResultjson.put("INDEX", Static.getDay());
            getResultjson.put("METHOD", "GetAuthInfo");
            getResultjson.put("PaymentMode", i + "");
            getResultjson.put("AuthCode", authCode);
            getResultjson.put("UserAccount", userName);
            RequestBody body = RequestBody.create(HTTPAPI.JSON, getResultjson.toString());
            Retrofit retrofit = new Retrofit.Builder().baseUrl(HTTPAPI.PAY_BASE_URL).build();
            IGetAuthInfo iGetAuthInfo = retrofit.create(IGetAuthInfo.class);
            Call<ResponseBody> authInfo = iGetAuthInfo.getAuthInfo(body);
            authInfo.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        String getAuthInfo = response.body().string();
                        L.d(L.TAG, "获取授权成功返回的结果" + getAuthInfo);
                        if (getAuthInfo.equals("")) {
                            Static.toast(CheckOutActivity.this, "网络繁忙");
                        } else {
                            JSONObject getAuthInfoJson = new JSONObject(getAuthInfo);
                            JSONArray data = getAuthInfoJson.getJSONArray("DATA");
                            if (data.length() == 0) {
                                Static.toast(CheckOutActivity.this, "授权失败");
                            } else {
                                //表示授权成功
                                JSONObject object = data.getJSONObject(0);
                                String name = object.getString("nick_name");
                                Message message = new Message();

                                if (i == 2) {
                                    message.what = CHANGE_UI_ALIPAY;
                                    message.obj = name;
                                    mHandler.sendMessage(message);
                                    APP.AlipayIsAuth = true;
                                    SharedPreferences.Editor edit = sharedPreferences.edit();
                                    edit.putString("alipayName", name);
                                    edit.commit();
                                } else if (i == 1) {
                                    message.what = CHANGE_UI_WX;
                                    message.obj = name;
                                    mHandler.sendMessage(message);
                                    APP.WXIsAuth = true;
                                    SharedPreferences.Editor edit = sharedPreferences.edit();
                                    edit.putString("WXName", name);
                                    edit.commit();
                                }
                            }
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    /**
     * 从后台拿到支付宝支付结果
     *
     * @param scan
     * @param order
     */
    private void getResult(ArrayList scan, String order) {
        //购物车里的所有商品码
        String s = Static.stringScan(scan);
        JSONObject object = new JSONObject();
        try {
            String encode = URLEncoder.encode(s, "utf-8");
            object.put("SOURCE", "CheckOutActivity");
            object.put("CREDENTIALS", "0");
            object.put("TERMINAL", "1");
            object.put("INDEX", Static.getDay());
            object.put("METHOD", "SelectOrder");
            object.put("DealNumber", order);
            object.put("CommodityCode", encode);
            RequestBody body = RequestBody.create(HTTPAPI.JSON, object.toString());
            Retrofit retrofit = new Retrofit.Builder().baseUrl(HTTPAPI.PAY_BASE_URL).build();
            IPaymentSelectOrder iPaymentSelectOrder = retrofit.create(IPaymentSelectOrder.class);
            Call<ResponseBody> call = iPaymentSelectOrder.SelectOrder(body);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    if (response == null) {
                    } else {
                        try {
                            String result = response.body().string();
                            if (result.equals("")) {
                                Static.toast(CheckOutActivity.this, "网络繁忙");
                            } else {
                                L.d(L.TAG, "支付返回结果" + result);
                                //支付返回结果{"DealStatus":"1","SOURCE":"CheckOutActivity","CREDENTIALS":"0","ADDRESS":"113.88.82.48","TERMINAL":"1","INDEX":"2017-12-19 02:31:08","METHOD":"SelectOrder","RETURNCODE":"200",
                                // "DATA":[["美年达","11","0.78"]]}
                                try {
                                    JSONObject js = new JSONObject(result);
                                    String dealStatus = js.getString("DealStatus");
                                    if (dealStatus.equals("2")) {
                                        //清空数据库里的数据
                                        new DBManger(CheckOutActivity.this).deleteSQL();
                                        //表示支付成功
                                        data = js.getJSONArray("DATA");
                                        if (data.length() == 0) {
                                            //表示没有红包，直接跳转到钱包界面
                                            startActivity(new Intent(CheckOutActivity.this, BillActivity.class));
                                            finish();
                                        } else {
                                            //表示有红包
                                            dialogLogin(data.getJSONArray(mI).getString(0), data.getJSONArray(mI).getString(3), data.getJSONArray(mI).getString(1), mI, data.length());
                                        }
                                    } else {
                                        //表示支付失败
                                        Static.toast(CheckOutActivity.this, "支付失败");
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }

                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
//            //   建行
//            case R.id.checkOut_bt_payByJianHang:
//                mInt = 0;
//                break;
            //微信
            case R.id.checkOut_bt_payByWeiXin:
                mInt = 1;
                break;
            //支付宝
            case R.id.checkOut_bt_payByZhiFuBao:
                mInt = 2;
                break;
            //平安
//            case R.id.checkOut_bt_payByPingAn:
//                mInt = 3;
//                break;
        }
    }

    //提示领取红包请求
    private void getHb(String userAccount, String hbId, final String hbMoney, final int i, final int dataLength) {
        ArrayList<String> keyList = new ArrayList<>();
        keyList.add("UserAccount");
        keyList.add("DistributeMoney");
        keyList.add("RedPacketId");
        ArrayList<String> valueList = new ArrayList<>();
        valueList.add(userAccount);
        valueList.add(hbMoney);
        valueList.add(hbId);
        List<List<String>> data = new ArrayList<>();
        data.add(keyList);
        data.add(valueList);
        String dataString = Static.string(data);
        L.d(L.TAG, "领取红包传过去的数据" + dataString);
        try {
            encodeHb = URLEncoder.encode(dataString, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        JSONObject jsonScan = new JSONObject();
        try {
            jsonScan.put("SOURCE", "CheckOutActivity");
            jsonScan.put("CREDENTIALS", "0");
            jsonScan.put("TERMINAL", "1");
            jsonScan.put("INDEX", Static.getDay());
            jsonScan.put("METHOD", "PacketRecord");
            jsonScan.put("DATA", encodeHb);
            RequestBody body = RequestBody.create(HTTPAPI.JSON, jsonScan.toString());
            Retrofit retrofit = new Retrofit.Builder().baseUrl(HTTPAPI.PAY_BASE_URL).build();
            IPacketRecord iPacketRecord = retrofit.create(IPacketRecord.class);
            Call<ResponseBody> call = iPacketRecord.packetRecord(body);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                    try {
                        String result = response.body().string();
                        L.d(L.TAG, "领取红包接口返回的数据" + result);
                        //{"DATA":["1"],"SOURCE":"CheckOutActivity","CREDENTIALS":"0","ADDRESS":"192.168.1.203","TERMINAL":"1","INDEX":"2017-12-19 07:29:09","METHOD":"PacketRecord"}
                        try {
                            JSONObject object = new JSONObject(result);
                            JSONArray d = object.getJSONArray("DATA");
                            if (d.getString(0).equals("1")) {
                                mI++;
                                dialogGetMoney(hbMoney, mI, dataLength);
                            } else if (d.getString(0).equals("0")) {
                                Static.toast(CheckOutActivity.this, "领取失败");
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //已登录dialog
    public void dialogLogin(final String account, final String money, final String hbId, final int i, final int dataLength) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.dialog_logined, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.Translucent_NoTitle);
        dialog = builder.create();
        dialog.setView(view);
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);
        ImageView ivAccount = (ImageView) view.findViewById(R.id.dialoged_iv_photo);
        ivAccount.setImageDrawable(getResources().getDrawable(R.drawable.logo));
        Button ivLogin = (Button) view.findViewById(R.id.dialoged_bt_open);//点击打开红包
        ivLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getHb(userName, hbId, money, i, dataLength);
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    //显示红包金额的dialog
    public void dialogGetMoney(final String money, final int i, final int dataLength) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.dialog_gethongbao, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.Translucent_NoTitle);
        dialog = builder.create();
        dialog.setView(view);
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);
        //设置红包金额
        TextView tvMoney = (TextView) view.findViewById(R.id.dialogGet_tv_money);
        tvMoney.setText(money);
        TextView tvMoneyAgain = (TextView) view.findViewById(R.id.dialogGet_tv_money);
        tvMoneyAgain.setText(money);
        dialog.show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                dialog.dismiss();
                //把红包金额存入余额
                SharedPreferences sharedPreferences = getSharedPreferences("userMassage", MODE_PRIVATE);
                String balance = sharedPreferences.getString("balance", "0.00");
                double moneyBalance = Double.parseDouble(balance);
                double moneyHongbao = Double.parseDouble(money);
                double sumMoney = moneyBalance + moneyHongbao;
                DecimalFormat df = new DecimalFormat("0.00");
                String format = df.format(sumMoney);
                SharedPreferences.Editor edit = sharedPreferences.edit();
                edit.putString("balance", format);
                edit.commit();
                L.d(L.TAG, "mI" + i + "红包数组的长度" + dataLength);
                if (i == dataLength) {
                    startActivity(new Intent(CheckOutActivity.this, BillActivity.class));
                    finish();
                } else if (i < dataLength) {
                    try {
                        dialogLogin(data.getJSONArray(mI).getString(0), data.getJSONArray(mI).getString(3), data.getJSONArray(mI).getString(1), mI, data.length());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, 2000);
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        if (getIntent().getStringExtra(Constant.formWXPay) != null) {
            L.d(L.TAG, "getIntent++++++++++" + getIntent().getStringExtra(Constant.formWXPay));
            if (getIntent().getStringExtra(Constant.formWXPay).equals(Constant.formWXPay)) {
                ArrayList scan = new ArrayList();
                for (int j = 0; j < query.size(); j++) {
                    scan.add(query.get(j).getScan());
                }
                //请求后台拿到支付结果
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        try {
                            sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
                getResult(scan, order);
            } else {
                String code = getIntent().getStringExtra(Constant.formWXAuth);
                getAuthResult(code, 1);
            }
        } else {
            L.d(L.TAG, "nullll" + getIntent().getStringExtra(Constant.formWXPay));
        }
    }

    @Subscribe          //订阅事件FirstEvent
    public void onEventMainThread(GetAuthCode code) {
        getAuthResult(code.getCode(), 1);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
